import pandas as pd


# 定义三张重点表的字段规则配置
SHEET_VALIDATION_CONFIG = {
    '企业基本信息': {
        '企业编码': ['unique_enterprise_code', 'length_check'],
        '数据日期': ['datetime']
    },
    '重大设备': {
        '设备编号': ['unique_device_code'],
        '数据日期': ['datetime']
    },
    '人员安全档案': {
        '员工卡号': ['unique_person_card'],
        '数据日期': ['datetime']
    }
}

# # 通用规则定义（支持传参）
# FIELD_VALIDATION_RULES = {
#     'datetime': {
#         'validate': lambda val, **kwargs: pd.notnull(val) if isinstance(val, pd.Timestamp)
#                                           else pd.notnull(pd.to_datetime(str(val), errors='coerce')),
#         'error_msg': lambda val: f"日期格式无效: {val}"
#     },

#     'unique_enterprise_code': {
#         'validate': lambda val, series, idx, **kwargs: not series.duplicated(keep=False).iloc[idx],
#         'error_msg': lambda val: f"企业编码重复: {val}"
#     },

#     'length_check': {
#         'validate': lambda val, **kwargs: (
#             pd.notna(val) and len(str(int(val))) == 12 if isinstance(val, (int, float)) else len(str(val).strip()) == 12
#         ),
#         'error_msg': lambda val: f"编码长度不符合要求: {val}"
#     },

#     'unique_device_code': {
#         'validate': lambda val, series, idx, **kwargs: not series.duplicated(keep=False).iloc[idx],
#         'error_msg': lambda val: f"设备编码重复: {val}"
#     },

#     'unique_person_card': {
#         'validate': lambda val, series, idx, **kwargs: not series.duplicated(keep=False).iloc[idx-1],
#         'error_msg': lambda val: f"人员卡号重复: {val}"
#     }
# }





# 通用规则定义（支持传参）
FIELD_VALIDATION_RULES = {
    'datetime': {
        'validate': lambda val, **kwargs: pd.notnull(val) if isinstance(val, pd.Timestamp)
                                          else pd.notnull(pd.to_datetime(str(val), errors='coerce')),
        'error_msg': lambda val: f"日期格式无效: {val}"
    },

    'unique_enterprise_code': {
        'validate': lambda val, series, idx, **kwargs: not series.duplicated(keep=False).iloc[idx],
        'error_msg': lambda val: f"企业编码重复: {val}"
    },

    'length_check': {
        'validate': lambda val, **kwargs: (
            pd.notna(val) and len(str(int(val))) == 12 if isinstance(val, (int, float)) else len(str(val).strip()) == 12
        ),
        'error_msg': lambda val: f"编码长度不符合要求: {val}"
    },

    'unique_device_code': {
        'validate': lambda val, series, idx, **kwargs: not series.duplicated(keep=False).iloc[idx],
        'error_msg': lambda val: f"设备编码重复: {val}"
    },

    'unique_person_card': {
        'validate': lambda val, series, idx, **kwargs: not series.duplicated(keep=False).iloc[idx-1],
        'error_msg': lambda val: f"人员卡号重复: {val}"
    }
}
